#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->stackedWidget->setCurrentWidget(ui->page);
    connect(ui->login,SIGNAL(clicked(bool)),this,SLOT(login_clicked()));
    connect(ui->cancle,SIGNAL(clicked(bool)),this,SLOT(cancle_clicked()));

    //打开摄像头
    if(cam.open(0))
    {
        cout<<"open success"<<endl;
    }
    else {
        cout<<"open error"<<endl;
    }
    timer = new QTimer(this);
    timer->start(40); //启动定时器，每40毫秒发送一次超时信号
    //connect(timer,SIGNAL(timeout()),this,SLOT(update()));
    connect(timer,&QTimer::timeout,this,&Widget::update);
    string model = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml";
    face = new Face(model);
    //将信号和槽连接
    //人脸检测前
    connect(this,&Widget::doDetect,face,&Face::detect);
    //人脸检测后
    connect(face,&Face::detected,this,&Widget::updateFace);
    //人脸识别前
    connect(this,&Widget::doRecongnize,face,&Face::recongnize);
    //人脸识别后
    connect(face,&Face::recongnized,this,&Widget::showuserid);
    timer = new QTimer();
    //每隔一秒调用一遍函数
    connect(timer,SIGNAL(timeout()),this,SLOT(showTime_slot()));
    timer->start(1000);



}

Widget::~Widget()
{
    delete ui;
}

void Widget::login_clicked()
{
    QString username=ui->username->text();
    QString password=ui->password->text();
    if(username=="admin"&&password=="111111")
    {
        ui->stackedWidget->setCurrentWidget(ui->page_2);

    }
       qDebug()<<"username:"<<username;
       qDebug()<<"password:"<<password;
}
void Widget::cancle_clicked()
{
    ui->username->clear();
    ui->password->clear();
}

void Widget::update()
{
    //从摄像头读取图像
    cv::Mat image;
    //>>输出重定向，将采集的视频保存在image
    cam >> image;
    frame++;
    if(frame >5)
    {
        frame = 0;
    }
    if((frame %5)==0)
    {

        emit doDetect(image); //发送人脸检测信号

    }
    if(hit==5)
    {
        Mat faceimg(image,range);//将检测到的人脸截取出来
        emit doRecongnize(faceimg);//发送人脸识别信号
    }
    cv::rectangle(image,range,CV_RGB(255,0,0));
    cv::cvtColor(image,image,CV_BGR2RGB);
    //将mat类型图像转换为QImage
    QImage qimage(image.data,image.cols,image.rows,image.step,QImage::Format_RGB888);
    ui->label->setPixmap(QPixmap::fromImage(qimage));


}
void Widget::updateFace(Rect face)
{
    range = face;//range用来存检测到的人脸
    //判断是否检测到人脸
    if(face!=Rect(0,0,0,0))
    {
        //如果检测到人脸
        hit++;
    }
    else {
        hit=0;
    }
}

void Widget::showuserid(Employee e)
{
    cout<<e.user_id<<endl;
    cout<<e.score<<endl;
    QString user;
    user=e.user_id.c_str();
    ui->label_2->setText(user);
    QString score = QString::number(e.score,'f',3);
    ui->label_3->setText(score);

}

void Widget::showTime_slot()
{
    //获得当前时间
    QDateTime time =QDateTime::currentDateTime();
    //按照某种格式输出 QDateTime 转化为Qstring
    QString str = time.toString("当前时间是： yyyy-MM-dd hh:mm:ss   dddd");
    ui->localtime->setText(str);
}

